﻿using Karbel.RFID;
using Org.LLRP.LTK.LLRPV1.Impinj;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;

namespace ConfExpert.Portable
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        int E = 0;
        int F = 0;
        int R = 0;
        int ER = 0;
        int FR = 0;
        int RR = 0;

        TagManager tm = null;
        private void frmMain_Load(object sender, EventArgs e)
        {
            DataSet result = DataAccess.GetSayimKontrol();
            dtKontrol = result.Tables[0];
            DataTable dtStatus = result.Tables[1];

            foreach (DataRow dr in dtStatus.Rows)
            {
                string tip = dr["Tip"].ToString();
                switch (tip)
                {
                    case "E":
                        E = (int)dr["Adet"];
                        break;
                    case "F":
                        F = (int)dr["Adet"];
                        break;
                    case "R":
                        R = (int)dr["Adet"];
                        break;
                }
            }

            lblInfo.Text = string.Format("Eksik:{0}/{1}  |  Fazla:{2}/{3}  |  Raf Hatası:{4}/{5}  |  Kalan:{6}", ER, E, FR, F, RR, R, E + F + R - ER - FR - RR);

            this.FormClosing += new FormClosingEventHandler(frmMain_FormClosing);
            StartRFID();
            //timerFake.Enabled = true;
        }

        private void StartRFID()
        {
            string ip1 = "10.0.1.42,87:1";
            tm = new TagManager(ENUM_ImpinjInventorySearchType.Dual_Target, ip1);
            tm.TagRead += tm_TagRead;
            tm.BoundForm = this;
        }

        void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        DataTable dtKontrol;
        int foundId = -1;
        int count = 0;
        List<Location> locs = new List<Location>();
        void tm_TagRead(Tag tag, double rssi)
        {
            //lblRollId.Text = tag.Id.ToString();
            if (foundId == -1)
            {
                DataRow[] drSelected = dtKontrol.Select(string.Format("RollId={0}", tag.Id));
                locs.Add(tag.LastMovement.Location);
                if (drSelected.Length > 0)
                {
                    count++;
                    locs.Add(tag.LastMovement.Location);
                    foundId = tag.Id;
                    DataSet ds = DataAccess.GetRollDetail(tag.Id);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataRow dr = ds.Tables[0].Rows[0];

                        object photo = ds.Tables[1].Rows[0]["Photo"];
                        if (ds.Tables[1].Rows.Count > 0 && photo != DBNull.Value)
                        {
                            byte[] bytes = (byte[])photo;
                            MemoryStream stream = new MemoryStream(bytes);
                            Bitmap image = new Bitmap(stream);
                            pb.Image = image;
                            pb.Visible = true;
                        }
                        else
                            pb.Visible = false;

                        string tip = drSelected[0]["Tip"].ToString().ToUpper();
                        btn1.Visible = btn2.Visible = true;
                        SetButtons(tip);
                        lblRollId.Text = dr["RollId"].ToString();
                        lblArtikel.Text = dr["Product"].ToString();
                        lblMarka.Text = dr["Brand"].ToString();

                        lblRaf.Text = dr["Shelf"].ToString() + " " + tag.LastMovement.Location;
                        lblMiktar.Text = dr["Qty"].ToString();
                        DataAccess.InsBuffer(lblRollId.Text);
                    }
                    else
                    {
                        pb.Visible = false;

                        string tip = drSelected[0]["Tip"].ToString().ToUpper();
                        btn1.Visible = btn2.Visible = true;
                        SetButtons(tip);
                        lblRollId.Text = tag.Id.ToString();


                        lblRaf.Text =  tag.LastMovement.Location.ToString();

                        //lblArtikel.Text = dr["Product"].ToString();
                        //lblMarka.Text = dr["Brand"].ToString();
                        //lblRaf.Text = dr["Shelf"].ToString();
                        //lblMiktar.Text = dr["Qty"].ToString();
                        //DataAccess.InsBuffer(lblRollId.Text);
                        DataAccess.InsBuffer(lblRollId.Text);
                    }
                    //timer.Stop();
                    //tm.Close();
                }
                /*
                else
                {
                    if (tag.Id >= 1000000000 && tag.Id <= 1000001000)//Raf etiketi
                    {
                        //
                    }
                    else // Geçersiz Roll ID
                    {
                        count++;
                        foundId = tag.Id;

                        pb.Visible = false;
                        string tip = "X";
                        btn1.Visible = btn2.Visible = true;
                        SetButtons(tip);
                        lblRollId.Text = tag.Id.ToString();
                        //timer.Stop();
                        tm.Close();
                    }
                }
                  * */
            }
            else if (foundId == tag.Id)
            {
                locs.Add(tag.LastMovement.Location);

                string antenler = "";
                foreach (Location l in locs)
                {
                    if (! lblRaf.Text.Contains(l.ToString()))
                    lblRaf.Text += l.ToString();
                    
                }
                
                //lblRaf.Text += " xxx:" + antenler;

                //string antenler = "";
                //foreach (Location l in locs)
                //{
                //    antenler = l.ToString();
                //}
                //lblRaf.Text += " Antenler:" + antenler;
                count = count + 1;
            }
        }

        private void SetButtons(string Tip)
        {
            switch (Tip)
            {
                case "E":
                    btn1.Text = "Sadece Raflandı";
                    btn1.Tag = 1;

                    btn2.Text = "Etiketi Değiştirilerek Raflandı";
                    btn2.Tag = 2;

                    lblTip.Text = "Eksik";
                    break;
                case "F":
                    btn1.Text = "Top Mevcut, Raflandı";
                    btn1.Tag = 3;

                    btn2.Text = "Geçersiz Etiket, Etiket Çıkartıldı";
                    btn2.Tag = 4;
                    lblTip.Text = "Fazla";
                    break;
                case "R":
                    btn1.Text = "Raf Bilgisi Doğru , Değişiklik Yapılmadı";
                    btn1.Tag = 5;

                    btn2.Text = "Raf Bilgisi Yanlış, Raflandı";
                    btn2.Tag = 6;
                    lblTip.Text = "Rafı Yanlış";
                    break;
                case "X":
                    btn1.Visible = false;

                    btn2.Text = "Geçersiz Etiket! Kaldırıldı";
                    btn2.Tag = 9;
                    lblTip.Text = "Geçersiz Etiket";
                    break;
            }
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            if (dtKontrol.Rows.Count > 0)
            {
                Random randomizer = new Random();
                int i = randomizer.Next(0, dtKontrol.Rows.Count);
                DataRow dr = dtKontrol.Rows[i];
                double rssi = 1;
                Tag tag = new Karbel.RFID.Tag();
                tag.Id = (int)dr["RollId"];
                tm_TagRead(tag, rssi);
            }
        }

        private void UpdateStatus(int SonucId)
        {
            int rollId = int.Parse(lblRollId.Text);
            DataAccess.UpdateSayimSonuc(rollId, SonucId);
            foreach (DataRow dr in dtKontrol.Rows)
            {
                if ((int)dr["RollId"] == rollId)
                {
                    dtKontrol.Rows.Remove(dr);
                    break;
                }
            }
            if (dtKontrol.Rows.Count > 0)
            {
                //timerFake.Start();
            }
            else
            {
                MessageBox.Show("Kontrol tamamlandı.");
                this.Close();
            }
            foundId = -1;
        }

        private void btn_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            int SonucId = (int)btn.Tag;
            UpdateStatus(SonucId);
            if (SonucId == 1 || SonucId == 2)
                ER++;
            else if (SonucId == 3 || SonucId == 4)
                FR++;
            else if (SonucId == 5 || SonucId == 6)
                RR++;

            lblInfo.Text = string.Format("Eksik:{0}/{1}  |  Fazla:{2}/{3}  |  Raf Hatası:{4}/{5}  |  Kalan:{6}", ER, E, FR, F, RR, R, E + F + R - ER - FR - RR);

            btn1.Visible = btn2.Visible = false;
            lblRollId.Text = "DOLAŞ";
            lblArtikel.Text = "Artikel";
            lblMarka.Text = "Marka";
            lblMiktar.Text = "Miktar";
            lblPower.Text = "0";
            lblRaf.Text = "Raf";
            lblTip.Text = "Tip";
            //StartRFID();
        }

        private void timerProggress_Tick(object sender, EventArgs e)
        {
            if (progressBar.Maximum < count)
                progressBar.Maximum = count;

            lblPower.Text = count.ToString();
            progressBar.Value = count;
            count = 0;

            locs = new List<Location>();
        }

        private void btnGec_Click(object sender, EventArgs e)
        {
            DataRow[] drs = dtKontrol.Select("RollId=" + foundId);
            if (drs.Length > 0)
            {
                foundId = -1;
                btn1.Visible = btn2.Visible = false;
                lblRollId.Text = "DOLAŞ";
                lblArtikel.Text = "Artikel";
                lblMarka.Text = "Marka";
                lblMiktar.Text = "Miktar";
                lblPower.Text = "0";
                lblRaf.Text = "Raf";
                lblTip.Text = "Tip";
                pb.Visible = false;


                dtKontrol.Rows.Remove(drs[0]);
            }
            
        }
    }
}
